package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {
    //读取配置文件中的路径
    @Value("${reggie.path}")
    private String bassDir;
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        //获取上传文件的文件名
        String fileName = file.getOriginalFilename();

        //获取文件扩展名
        String fileExtName = fileName.substring(fileName.lastIndexOf("."));
        //创建唯一新的文件名
        String newFileName = UUIDUtils.getUUID()+fileExtName;

        //将文件保存到目录下
        File dir = new File(bassDir);
        if (!dir.exists()){
            dir.mkdir();
        }
        file.transferTo(new File(bassDir+newFileName));
        return R.success(newFileName);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {
        //输入流
        FileInputStream inputStream = new FileInputStream(bassDir + fileName);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将输入流输出给输出流
        IOUtils.copy(inputStream,outputStream);
    }

}
